<?php

class OauthAction extends BaseAction {

    public function index() {
        switch ($_GET['type']) {
            case 'weibo':
                $this->performWeibo();
                break;
            case 'baidu':
                $this->performBaidu();
                break;
            case 'qq':
                $this->performQq();
                break;
            case 'kaixin':
                $this->performKaixin();
                break;
            default:
        }
    }

    public function performKaixin() {
        include COMMON_PATH . 'oauth2/kaixin/kxoauth/kxClient.php';
        if (array_key_exists('code', $_GET)) {
            $connect = new KXClient();
            $response = $connect->getAccessTokenFromCode($_GET['code']);
            var_dump($response);
            exit;
            if (isset($response->access_token)) {
                session_start();
                $_SESSION['access_token'] = $response->access_token;
                $_SESSION['refresh_token'] = $response->refresh_token;
                header("Location:index.php");
            }
        } elseif (array_key_exists('access_token', $_GET)) {
            session_start();
            $_SESSION['access_token'] = $_GET['access_token'];
            $_SESSION['refresh_token'] = $_GET['refresh_token'];
            header("Location:index.php");
        }









        include COMMON_PATH . 'oauth2/kaixin/kxoauth/kxClient.php';
        import('@.ORG.Session');
        $connection = new KXClient();

        $scope = 'create_records create_album user_photo friends_photo upload_photo';
        $connection->getAuthorizeURL('code', $scope);


        $data['open_id'] = $user_message['idstr'];
        $data['from'] = 'weibo';
        $data['figureurl'] = $user_message['profile_image_url'];
        $data['gender'] = $user_message['gender'];
        $member_extend = M("Member_extend");
        $memberVerify = $member_extend->getByOpen_id($data['open_id']);

        if (empty($memberVerify)) {

            $member = M("Member");
            $mdata['username'] = $user_message['name'];

            $data['member_id'] = $member->add($mdata);

            if ($member_extend->add($data)) {
                Session::set(C('USER_AUTH_KEY'), $data['member_id']);
                $this->redirect(__APP__ . '/membercenter/');
            } else {
                echo $member_extend->getLastSql();
            }
        } else {
            Session::set(C('USER_AUTH_KEY'), $memberVerify['member_id']);
            $this->redirect(__APP__ . '/membercenter/');
        }
    }

//    Array
//(
//    [id] => 1715970242
//    [idstr] => 1715970242
//    [screen_name] => 温柔的大海
//    [name] => 温柔的大海
//    [province] => 11
//    [city] => 5
//    [location] => 北京 朝阳区
//    [description] => 一个打杂的
//    [url] => http://blog.quwanma.com
//    [profile_image_url] => http://tp3.sinaimg.cn/1715970242/50/5632818452/1
//    [profile_url] => 33kuai
//    [domain] => 33kuai
//    [weihao] => 
//    [gender] => m
//    [followers_count] => 215
//    [friends_count] => 151
//    [statuses_count] => 456
//    [favourites_count] => 0
//    [created_at] => Sun Mar 21 23:29:35 +0800 2010
//    [following] => 
//    [allow_all_act_msg] => 1
//    [geo_enabled] => 1
//    [verified] => 
//    [verified_type] => -1
//    [remark] => 
//    [status] => Array
//        (
//            [created_at] => Sun Jun 17 20:50:11 +0800 2012
//            [id] => 3458010494055982
//            [mid] => 3458010494055982
//            [idstr] => 3458010494055982
//            [text] => [不好意思]
//            [source] => <a href="http://weibo.com" rel="nofollow">新浪微博</a>
//            [favorited] => 
//            [truncated] => 
//            [in_reply_to_status_id] => 
//            [in_reply_to_user_id] => 
//            [in_reply_to_screen_name] => 
//            [geo] => 
//            [retweeted_status] => Array
//                (
//                    [created_at] => Sun Jun 17 20:48:56 +0800 2012
//                    [id] => 3458010179670073
//                    [mid] => 3458010179670073
//                    [idstr] => 3458010179670073
//                    [text] => “被强迫洗澡这事吧，既然无力反抗，不如学会享受~”——zz
//                    [source] => <a href="http://weibo.com" rel="nofollow">新浪微博</a>
//                    [favorited] => 
//                    [truncated] => 
//                    [in_reply_to_status_id] => 
//                    [in_reply_to_user_id] => 
//                    [in_reply_to_screen_name] => 
//                    [thumbnail_pic] => http://ww2.sinaimg.cn/thumbnail/61bb1494jw1du1g3bw76xj.jpg
//                    [bmiddle_pic] => http://ww2.sinaimg.cn/bmiddle/61bb1494jw1du1g3bw76xj.jpg
//                    [original_pic] => http://ww2.sinaimg.cn/large/61bb1494jw1du1g3bw76xj.jpg
//                    [geo] => 
//                    [user] => Array
//                        (
//                            [id] => 1639650452
//                            [idstr] => 1639650452
//                            [screen_name] => 围脖画报
//                            [name] => 围脖画报
//                            [province] => 11
//                            [city] => 1000
//                            [location] => 北京
//                            [description] => 猫咪等宠物、趣图、创意设计等内容，欢迎关注~ 对这个卖萌的世界绝望鸟(￣▽￣")
//                            [url] => http://weibo.com/iammj
//                            [profile_image_url] => http://tp1.sinaimg.cn/1639650452/50/5631759833/1
//                            [profile_url] => fightingyouth
//                            [domain] => fightingyouth
//                            [weihao] => 
//                            [gender] => m
//                            [followers_count] => 151374
//                            [friends_count] => 1814
//                            [statuses_count] => 15193
//                            [favourites_count] => 91
//                            [created_at] => Fri Aug 28 16:34:56 +0800 2009
//                            [following] => 
//                            [allow_all_act_msg] => 1
//                            [geo_enabled] => 1
//                            [verified] => 
//                            [verified_type] => -1
//                            [allow_all_comment] => 1
//                            [avatar_large] => http://tp1.sinaimg.cn/1639650452/180/5631759833/1
//                            [verified_reason] => 
//                            [follow_me] => 
//                            [online_status] => 0
//                            [bi_followers_count] => 1649
//                            [lang] => zh-cn
//                        )
//
//                    [reposts_count] => 0
//                    [comments_count] => 0
//                    [mlevel] => 0
//                    [visible] => Array
//                        (
//                            [type] => 0
//                            [list_id] => 0
//                        )
//
//                )
//
//            [reposts_count] => 0
//            [comments_count] => 0
//            [mlevel] => 0
//            [visible] => Array
//                (
//                    [type] => 0
//                    [list_id] => 0
//                )
//
//        )
//
//    [allow_all_comment] => 1
//    [avatar_large] => http://tp3.sinaimg.cn/1715970242/180/5632818452/1
//    [verified_reason] => 
//    [follow_me] => 
//    [online_status] => 0
//    [bi_followers_count] => 57
//    [lang] => zh-cn
//)

    public function performWeibo($param) {
        include COMMON_PATH . 'oauth2/weibo/config.php';
        include COMMON_PATH . 'oauth2/weibo/saetv2.ex.class.php';
        import('@.ORG.Session');
        $o = new \SaeTOAuthV2(WB_AKEY, WB_SKEY);

        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = WB_CALLBACK_URL;
            try {
                $token = $o->getAccessToken('code', $keys);
            } catch (\OAuthException $e) {
                
            }
        }

        $_SESSION['token'] = $token;

        $Oauthmember = D("Oauthmember");
        $Oauthm = $Oauthmember->getByOauth_id($_SESSION['token']['uid']);
        $c = new \SaeTClientV2(WB_AKEY, WB_SKEY, $_SESSION['token']['access_token']);
        $uid_get = $c->get_uid();
        $uid = $uid_get['uid'];
        $user_message = $c->show_user_by_id($uid);

        $data['open_id'] = $user_message['idstr'];
        $data['from'] = 'weibo';
        $data['figureurl'] = $user_message['profile_image_url'];
        $data['gender'] = $user_message['gender'];
        $member_extend = M("Member_extend");
        $memberVerify = $member_extend->getByOpen_id($data['open_id']);

        if (empty($memberVerify)) {

            $member = M("Member");
            $mdata['username'] = $user_message['name'];

            $data['member_id'] = $member->add($mdata);

            if ($member_extend->add($data)) {
                Session::set(C('USER_AUTH_KEY'), $data['member_id']);
                $this->redirect(__APP__ . '/membercenter/');
            } else {
                echo $member_extend->getLastSql();
            }
        } else {
            Session::set(C('USER_AUTH_KEY'), $memberVerify['member_id']);
            $this->redirect(__APP__ . '/membercenter/');
        }


//print_r($user_message);exit;
//$c->update( '我是来测试的' );exit;
//        if (!is_null($Oauthm)) {
//            Session::set(C('USER_AUTH_KEY'), $Oauthm['oauth_id']);
//            Session::set('name', $Oauthm['name']);
//        } else {
//            $c = new SaeTClientV2(WB_AKEY, WB_SKEY, $_SESSION['token']['access_token']);
//            $ms = $c->home_timeline(); // done
//            $uid_get = $c->get_uid();
//            $uid = $uid_get['uid'];
//            $user_message = $c->show_user_by_id($uid); //根据ID获取用户等基本信息
//            print_r($user_message);exit;
//            $Oauthmember = D("Oauthmember");
//            $Oauthmember->Create();
//            $Oauthmember->oauth_id = $uid;
//            $Oauthmember->name = $user_message['name'];
//            $Oauthmember->type = $_GET['type'];
//            $Oauthmember->gender = $user_message['gender'];
//            $id = $Oauthmember->add();
//            $Oauthmember = D("Oauthmember");
//            $new = $Oauthmember->getById($id);
//            Session::set(C('USER_AUTH_KEY'), $new['oauth_id']);
//            Session::set('name', $new['name']);
//        }
        //    $this->redirect(__APP__ . '/membercenter/');
    }

    public function performRenren() {
        include COMMON_PATH . 'oauth2/renren/class/config.inc.php';
        include COMMON_PATH . 'oauth2/renren/class/RenrenOAuthApiService.class.php';
        include COMMON_PATH . 'oauth2/renren/class/RenrenRestApiService.class.php';
        $access_token = '184484|6.ef5bcd1592c3017f512474324554f5f8.2592000.1334664000-251263712';
        $restApi = new RenrenRestApiService;
        $params = array('fields' => 'uid,name,sex,birthday,mainurl,hometown_location,university_history,tinyurl,headurl', 'access_token' => $access_token);
        $res = $restApi->rr_post_curl('users.getInfo', $params); //curl函数发送请求
//$res = $restApi->rr_post_fopen('users.getInfo', $params);//如果你的环境无法支持curl函数，可以用基于fopen函数的该函数发送请求
        var_dump($res);
        exit; //输出返回的结果
        $code = $_GET["code"];
        include COMMON_PATH . 'oauth2/renren/class/config.inc.php';
        include COMMON_PATH . 'oauth2/renren/class/RenrenOAuthApiService.class.php';
        include COMMON_PATH . 'oauth2/renren/class/RenrenRestApiService.class.php';


        if ($code) {
            echo '<hr>';
            echo '华丽的分割线';
            echo '<hr>使用code换取accesstoken：<br>';
//获取accesstoken
            $oauthApi = new RenrenOAuthApiService;
            $post_params = array('client_id' => $config->APIKey,
                'client_secret' => $config->SecretKey,
                'redirect_uri' => $config->redirecturi,
                'grant_type' => 'authorization_code',
                'code' => $code
            );
            $token_url = 'http://graph.renren.com/oauth/token';
            $access_info = $oauthApi->rr_post_curl($token_url, $post_params); //使用code换取token
//$access_info=$oauthApi->rr_post_fopen($token_url,$post_params);//如果你的环境无法支持curl函数，可以用基于fopen函数的该函数发送请求
            $access_token = $access_info["access_token"];
            $expires_in = $access_info["expires_in"];
            $refresh_token = $access_info["refresh_token"];
//session_start();

            $_SESSION["access_token"] = $access_token;
            echo 'access_token:' . $access_token . '<br>';
            echo 'expires_in:' . $expires_in . '<br>';
            echo 'refresh_token:' . $refresh_token . '<br>';
            echo '<hr>';
            echo '华丽的分割线';
            echo '<hr>使用accesstoken获取登录用户的信息：<br>';
//获取用户信息RenrenRestApiService
            $access_token = '184484|6.ef5bcd1592c3017f512474324554f5f8.2592000.1334664000-251263712';
            $restApi = new RenrenRestApiService;
            $params = array('fields' => 'uid,name,sex,birthday,mainurl,hometown_location,university_history,tinyurl,headurl', 'access_token' => $access_token);
            $res = $restApi->rr_post_curl('users.getInfo', $params); //curl函数发送请求
//$res = $restApi->rr_post_fopen('users.getInfo', $params);//如果你的环境无法支持curl函数，可以用基于fopen函数的该函数发送请求


            $userId = $res[0]["uid"];
            $username = $res[0]["name"];
            $birthday = $res[0]["birthday"];
            $tinyurl = $res[0]["tinyurl"];
            $sex = $res[0]["sex"];
            $headurl = $res[0]["headurl"];
            $mainurl = $res[0]["mainurl"];
            echo "userId:" . $userId . '<br>';
            echo "username:" . $username . '<br>';
            echo "sex:" . $sex . '<br>';
            echo "birthday:" . $birthday . '<br>';
            echo "tinyurl:" . $tinyurl . '<br>';
            echo "headurl:" . $headurl . '<br>';
            echo "mainurl:" . $mainurl . '<br>';
            if (true) {//如果userId已经存在
                //更新数据库的access_token、expires_in、refresh_token、获取token的时间
                //直接登录到网站
            } else {
                //注册网站或者绑定已有账号
                //进行同步设置？
                //登录到网站
            }
            echo '<hr>';
            echo '华丽的分割线';
            echo '<hr>使用refreshtoken刷新accesstoken：<br>';
//刷新代码：
//用refreshtoken刷新accesstoken（在同步新鲜事的时候取出对应网站用户的人人accesstoken，如果用当前时间的秒数-expires_in>获取token的时间的秒数,则accesstoken过期，用refreshtoken刷新accesstoken）

            $post_params = array('client_id' => $config->APIKey,
                'client_secret' => $config->SecretKey,
                'refresh_token' => $refresh_token,
                'grant_type' => 'refresh_token'
            );
            $access_info = $oauthApi->rr_post_curl($token_url, $post_params); //使用code换取token
            $access_token = $access_info["access_token"];
            $expires_in = $access_info["expires_in"];
            $refresh_token = $access_info["refresh_token"];
            echo 'access_token:' . $access_token . '<br>';
            echo 'expires_in:' . $expires_in . '<br>';
            echo 'refresh_token:' . $refresh_token . '<br>';
        } else {
            //如果获取不到code，将错误信息打出来
            echo 'errorparameter code is null:<br>' . $_SERVER["QUERY_STRING"];
        }
//下面是同步的代码，因为用到access_token，所以写在获取access_token的页面中，真正同步时应该从数据库中取的access_token（判断access_token是否过期，过期就用refreshtoken刷新，刷新代码在上面，并将刷新的access_token、expires_in、refresh_token替换掉数据库中的）

        echo '<hr>';
        echo '华丽的分割线';
        echo '<hr>';
    }

//    Array
//(
//    [ret] => 0
//    [msg] => 
//    [nickname] => 温柔的大海
//    [figureurl] => http://qzapp.qlogo.cn/qzapp/100280653/E3D2E469A33C6E5CE7A691C10BF0E813/30
//    [figureurl_1] => http://qzapp.qlogo.cn/qzapp/100280653/E3D2E469A33C6E5CE7A691C10BF0E813/50
//    [figureurl_2] => http://qzapp.qlogo.cn/qzapp/100280653/E3D2E469A33C6E5CE7A691C10BF0E813/100
//    [gender] => 男
//    [vip] => 0
//    [level] => 0
//)
    public function performQq() {
        include COMMON_PATH . 'oauth2/qq/comm/config.php';
        include COMMON_PATH . 'oauth2/qq/comm/utils.php';
        if ($_REQUEST['state'] == $_SESSION['state']) { //csrf
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                    . "client_id=" . $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"])
                    . "&client_secret=" . $_SESSION["appkey"] . "&code=" . $_REQUEST["code"];

            $response = get_url_contents($token_url);
            if (strpos($response, "callback") !== false) {
                $lpos = strpos($response, "(");
                $rpos = strrpos($response, ")");
                $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
                $msg = json_decode($response);
                if (isset($msg->error)) {
                    echo "<h3>error:</h3>" . $msg->error;
                    echo "<h3>msg  :</h3>" . $msg->error_description;
                    exit;
                }
            }

            $params = array();
            parse_str($response, $params);

            //debug
            //print_r($params);
            //set access token to session
            $_SESSION["access_token"] = $params["access_token"];
        } else {
            echo("The state does not match. You may be a victim of CSRF.");
        }

        $this->get_openid();
        $get_user_info = "https://graph.qq.com/user/get_user_info?"
                . "access_token=" . $_SESSION['access_token']
                . "&oauth_consumer_key=" . $_SESSION["appid"]
                . "&openid=" . $_SESSION["openid"]
                . "&format=json";

        $info = get_url_contents($get_user_info);
        $arr = json_decode($info, true);


        $data['open_id'] = $this->get_openid();
        $data['from'] = 'qq';
        $data['figureurl'] = $arr['figureurl_2'];
        $data['nickname'] = $arr['nickname'];
        $data['gender'] = $arr['gender'];


        $member_extend = M("Member_extend");
        $memberVerify = $member_extend->getByOpen_id($data['open_id']);

        if (empty($memberVerify)) {

            $member = M("Member");
            $mdata['username'] = $arr['nickname'];

            $data['member_id'] = $member->add($mdata);

            if ($member_extend->add($data)) {
                Session::set(C('USER_AUTH_KEY'), $data['member_id']);
                $this->redirect(__APP__ . '/membercenter/');
            } else {
                echo $member_extend->getLastSql();
            }
        } else {
            Session::set(C('USER_AUTH_KEY'), $memberVerify['member_id']);
            $this->redirect(__APP__ . '/membercenter/');
        }


        //获取用户标示id
    }

    function qq_callback() {
        //debug
        //print_r($_REQUEST);
        //print_r($_SESSION);

        if ($_REQUEST['state'] == $_SESSION['state']) { //csrf
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                    . "client_id=" . $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"])
                    . "&client_secret=" . $_SESSION["appkey"] . "&code=" . $_REQUEST["code"];

            $response = get_url_contents($token_url);
            print_r($response);
            exit;
            if (strpos($response, "callback") !== false) {
                $lpos = strpos($response, "(");
                $rpos = strrpos($response, ")");
                $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
                $msg = json_decode($response);
                if (isset($msg->error)) {
                    echo "<h3>error:</h3>" . $msg->error;
                    echo "<h3>msg  :</h3>" . $msg->error_description;
                    exit;
                }
            }

            $params = array();
            parse_str($response, $params);

            //debug
            //print_r($params);
            //set access token to session
            $_SESSION["access_token"] = $params["access_token"];
        } else {
            echo("The state does not match. You may be a victim of CSRF.");
        }
    }

    function get_openid() {
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token="
                . $_SESSION['access_token'];

        $str = get_url_contents($graph_url);
        if (strpos($str, "callback") !== false) {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str = substr($str, $lpos + 1, $rpos - $lpos - 1);
        }

        $user = json_decode($str);
        if (isset($user->error)) {
            echo "<h3>error:</h3>" . $user->error;
            echo "<h3>msg  :</h3>" . $user->error_description;
            exit;
        }

        //debug
        return $user->openid;
//        echo("Hello " . $user->openid);
//        //set openid to session
//        $_SESSION["openid"] = $user->openid;
    }

//    
//    {
//    "userid":"2097322476",
//    "username":"wl19871011",
//    "realname":"阳光",
//    "userdetail":"喜欢自由",
//    "birthday":"1987-01-01",
//    "marriage":"恋爱",
//    "sex":"男",
//    "blood":"O",
//    "constellation":"射手",
//    "figure":"小巧",
//    "education":"大学/专科",
//    "trade":"计算机/电子产品",
//    "job":"未知",
//    "birthday_year":"1987",
//    "birthday_month":"01",
//    "birthday_day":"01",
//}
    private function performBaidu() {

        include COMMON_PATH . 'oauth2/baidu/Baidu.php';
        include COMMON_PATH . 'oauth2/weibo/BaiduStore.php';
        import('@.ORG.Session');
        $baidu = new Baidu('llYR1Ba1cZ3uwEX4tcbO6QL5', 'obh5DcqzusMmhxrlh8tlGYjHYt5px5OS',
                        new BaiduSessionStore('llYR1Ba1cZ3uwEX4tcbO6QL5'));
        $baidu->useHttps();
        $user = $baidu->getLoggedInUser();
        if ($user) {
            $user_profile = $baidu->api('passport/users/getInfo', array('fields' => 'userid,username,portrait,sex,birthday'));

            $data['open_id'] = $user_profile['userid'];
            $data['from'] = 'baidu';
            $data['figureurl'] = 'http://himg.bdimg.com/sys/portraitn/item/' . $user_profile['portrait'] . '.jpg';
            $data['nickname'] = $user_profile['username'];
            $data['gender'] = $user_profile['sex'];


            $member_extend = M("Member_extend");
            $memberVerify = $member_extend->getByOpen_id($data['open_id']);

            if (empty($memberVerify)) {

                $member = M("Member");
                $mdata['username'] = $data['nickname'];

                $data['member_id'] = $member->add($mdata);

                if ($member_extend->add($data)) {
                    Session::set(C('USER_AUTH_KEY'), $data['member_id']);
                    $this->redirect(__APP__ . '/membercenter/');
                } else {
                    echo $member_extend->getLastSql();
                }
            } else {
                Session::set(C('USER_AUTH_KEY'), $memberVerify['member_id']);
                $this->redirect(__APP__ . '/membercenter/');
            }




            if ($user_profile === false) {
                //get user profile failed
                var_dump(var_export(array('errcode' => $baidu->errcode(), 'errmsg' => $baidu->errmsg()), true));
                $user = null;
            }
        }
    }

}

?>